/**
 * Copyright (c) 2004-2016 All Rights Reserved.
 */
package com.zbest.zpay.integration.aliyun;

import java.io.Serializable;

import net.spy.memcached.AddrUtil;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.ConnectionFactoryBuilder.Protocol;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.auth.AuthDescriptor;
import net.spy.memcached.auth.PlainCallbackHandler;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.zbest.common.lang.serialize.HessianSerializeUtil;

/**
 * 
 *
 * @author czhou3306@gmail.com
 * @version $Id: AliyunOCSClientImpl.java, v0.1 2016年2月19日 上午9:20:46 czhou3306@gmail.com Exp $
 */
@Service("aliyunOCSClient")
public class AliyunOCSClientImpl implements AliyunOCSClient {

    private static final Logger logger     = LoggerFactory.getLogger(AliyunOCSClientImpl.class);

    private String              host       = "425a0a51c35f433c.m.cnhzaliqshpub001.ocs.aliyuncs.com"; //控制台上的“内网地址”
    private String              port       = "11211";                                               //默认端口 11211，不用改
    private String              username   = "425a0a51c35f433c";                                    //控制台上的“访问账号”
    private String              password   = "Chenzhou0714";                                        //邮件中提供的“密码”
    private int                 expireTime = 1000;                                                  // 过期时间，单位s

    /** 
     * @see com.zbest.zpay.integration.aliyun.AliyunOCSClient#putData(java.lang.String, java.lang.Object)
     */
    @Override
    public void putData(String key, Object value) {
        logger.info("putOcs,key=" + key);
        MemcachedClient cache = null;
        try {
            cache = buildClient();
            Boolean result = cache.set(key, expireTime,
                HessianSerializeUtil.serialize((Serializable) value)).get();
            logger.info("putOcs结果result=" + result);
        } catch (Exception e) {
            logger.error("往memcache中存放数据库异常key=" + key, e);
        } finally {
            if (cache != null) {
                cache.shutdown();
            }
        }

    }

    /** 
     * @see com.zbest.zpay.integration.aliyun.AliyunOCSClient#putData(java.lang.String, java.lang.Object, long)
     */
    @Override
    public void putData(String key, Object value, int timeout) {

        logger.info("putOcs,key=" + key);

        MemcachedClient cache = null;
        try {
            cache = buildClient();
            Boolean result = cache.set(key, timeout,
                HessianSerializeUtil.serialize((Serializable) value)).get();
            logger.info("putOcs结果result=" + result);
        } catch (Exception e) {
            logger.error("往memcache中存放数据库异常key=" + key, e);
        } finally {
            if (cache != null) {
                cache.shutdown();
            }
        }

    }

    /** 
     * @see com.zbest.zpay.integration.aliyun.AliyunOCSClient#getData(java.lang.String)
     */
    @Override
    public Object getData(String key) {
        logger.info("getOcs,key=" + key);
        MemcachedClient cache = null;
        try {
            if (StringUtils.isBlank(key)) {
                return null;
            }
            cache = buildClient();
            Object cacheObject = cache.get(key);
            if (cacheObject != null) {
                Object object = HessianSerializeUtil.deserialize((byte[]) cacheObject);
                logger.info("getOcs,key=" + key + ",object=" + object);
                return object;
            } else {
                return null;
            }
        } catch (Exception e) {
            logger.error("获取数据异常key=" + key, e);
            throw new RuntimeException(e);
        } finally {
            if (cache != null) {
                cache.shutdown();
            }
        }

    }

    /** 
     * @see com.zbest.zpay.integration.aliyun.AliyunOCSClient#remove(java.lang.String)
     */
    @Override
    public void remove(String key) {

        MemcachedClient cache = null;
        try {
            cache = buildClient();
            cache.delete(key);
        } catch (Exception e) {
            logger.error("获取数据异常key=" + key, e);
            throw new RuntimeException(e);
        } finally {
            if (cache != null) {
                cache.shutdown();
            }
        }

    }

    private MemcachedClient buildClient() throws Exception {
        AuthDescriptor ad = new AuthDescriptor(new String[] { "PLAIN" }, new PlainCallbackHandler(
            username, password));

        return new MemcachedClient(new ConnectionFactoryBuilder().setProtocol(Protocol.BINARY)
            .setAuthDescriptor(ad).build(), AddrUtil.getAddresses(host + ":" + port));
    }

    /** 
     * @see com.zbest.zpay.integration.aliyun.AliyunOCSClient#expire(java.lang.String, int)
     */
    @Override
    public void expire(String key, int expireTime) {

        MemcachedClient cache = null;
        try {
            cache = buildClient();
            cache.touch(key, expireTime);
        } catch (Exception e) {
            logger.error("重新设置时间异常key=" + key, e);
            throw new RuntimeException(e);
        } finally {
            if (cache != null) {
                cache.shutdown();
            }
        }

    }
}
